# PowerShell 版本的AI服务启动脚本
Set-Location "d:\code\learning-platform\ai"

Write-Host "==================================="
Write-Host "🚀 启动AI服务 (PowerShell版本)"
Write-Host "📁 当前目录: $(Get-Location)"
Write-Host "==================================="

# 1. 检查Python是否安装
Write-Host "🔍 检查Python安装情况..."
Try {
    $pythonVersion = python --version 2>&1
    Write-Host "✅ Python版本: $pythonVersion"
} Catch {
    Write-Host "❌ 未找到Python，请先安装Python 3.9+"
    Read-Host -Prompt "按Enter键退出"
    exit 1
}

# 2. 创建虚拟环境
Write-Host "💻 创建Python虚拟环境..."
if (-not (Test-Path ".venv")) {
    python -m venv .venv
    if ($LASTEXITCODE -ne 0) {
        Write-Host "❌ 创建虚拟环境失败"
        Read-Host -Prompt "按Enter键退出"
        exit 1
    }
    Write-Host "✅ 虚拟环境创建成功"
} else {
    Write-Host "✅ 虚拟环境已存在，跳过创建"
}

# 3. 激活虚拟环境
Write-Host "⚡ 激活虚拟环境..."
$activateScript = ".venv\Scripts\Activate.ps1"
if (Test-Path $activateScript) {
    . $activateScript
    Write-Host "✅ 虚拟环境已激活"
} else {
    Write-Host "❌ 激活虚拟环境失败: 未找到Activate.ps1"
    Read-Host -Prompt "按Enter键退出"
    exit 1
}

# 4. 升级pip
Write-Host "🔄 升级pip..."
python -m pip install --upgrade pip
if ($LASTEXITCODE -ne 0) {
    Write-Host "⚠️ pip升级失败，但尝试继续"
}

# 5. 安装依赖
Write-Host "📦 安装项目依赖..."
# 先安装Pillow 11.0.0，因为它与Python 3.13更兼容
pip install pillow==11.0.0
if ($LASTEXITCODE -ne 0) {
    Write-Host "⚠️ Pillow安装失败，尝试使用10.0.1版"
    pip install pillow==10.0.1
}

# 安装其他依赖
Write-Host "📚 安装requirements.txt中的所有依赖..."
pip install -r requirements.txt
if ($LASTEXITCODE -ne 0) {
    Write-Host "❌ 依赖安装失败，尝试单独安装关键包"
    pip install fastapi uvicorn[standard]==0.24.0 langchain==0.0.352 langchain-community==0.0.3 chromadb==0.4.18 sentence-transformers==2.2.2
}

# 6. 设置环境变量
Write-Host "🔧 设置环境变量..."
$env:QWEN_API_KEY = "your_qwen_api_key_here"
$env:OPENAI_API_KEY = "your_openai_api_key_here"
$env:DEEPSEEK_API_KEY = "your_deepseek_api_key_here"
$env:AI_HOST = "0.0.0.0"
$env:AI_PORT = "8000"
$env:AI_CORS_ORIGINS = "*"

# 7. 启动服务
Write-Host "🚀 启动AI服务..."
Write-Host "📝 服务将在 http://localhost:8000 运行"
Write-Host "📋 访问 http://localhost:8000/ai/health 检查服务状态"
Write-Host "==================================="

python main.py
if ($LASTEXITCODE -ne 0) {
    Write-Host "❌ AI服务启动失败"
    Read-Host -Prompt "按Enter键退出"
    exit 1
}

# 8. 服务结束后清理
Write-Host "🛑 AI服务已停止"
deactivate
Read-Host -Prompt "按Enter键退出"